#!   /usr/bin/env   python3
#    coding: utf8
import socket
import time
import sys


class eb_server(object):
    """docstring for eb_server"""

    def __init__(self, my_ip, my_port):
        self.local_addr = (my_ip, my_port)

    def open(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(self.local_addr)

    def close(self):
        self.socket.close()

    def sent_message(self, buf, d_ip, d_port):
        try:
            self.socket.sendto(buf.encode(), (d_ip, d_port))
        except:
            print("Eroor1")

    def receive_message(self):
        receive_data = self.socket.recvfrom(1024)
        receive_content = receive_data[0]
        receive_localAddr = receive_data[1]
        print(receive_localAddr)
        recv_buf = ""
        recv_message = []
        for i in range(len(receive_content)):
            recv_message.append(ord(receive_content[i]))
            recv_buf = recv_buf + (hex(ord(receive_content[i]))) + " "
        print(recv_buf)
        return recv_message


def trigger(inp):
    try:
        trigger_delay_sec = 1
        trigger_channel = 1
        d_ip = "192.168.6.24"
        d_port = 8009

        if inp == "close".upper():
            trigger_switch = 0x00
            trigger_pattern = 0x01
            msg = "close".upper()
        elif inp == "ac".upper():
            trigger_switch = 0x01
            trigger_pattern = 0x01
            msg = "ac".upper()
        elif inp == "vme".upper():
            trigger_switch = 0x01
            trigger_pattern = 0x00
            msg = "vme".upper()

        my_eb = eb_server("192.168.6.29", 42595)
        my_eb.open()

        eb_write = [0x4e, 0x7f, 0x00, trigger_switch,
                    0x00, 0x00, 0x00, trigger_pattern]
        eb_buf = ""
        for i in range(len(eb_write)):
            eb_buf = eb_buf + chr(eb_write[i])
        my_eb.sent_message(eb_buf, d_ip, d_port)
        #print([hex(i) for i in eb_write])
        print("当前模式:\t{}".format(msg))
    except:
        print("Eroor2")
    finally:
        # print("close!")
        my_eb.close()


if __name__ == "__main__":
    if len(sys.argv) == 2:
        inp = sys.argv[1]
        trigger(inp.upper())
    else:
        print("请输入参数")
